package cn.com.bluemoon.daps.sync.core.sync.log;

import cn.com.bluemoon.daps.common.toolkit.BmAssetUtils;
import cn.com.bluemoon.daps.sync.core.sync.GlobalConfig;
import cn.com.bluemoon.daps.sync.entity.DapSyncProdEnvTaskDetail;
import lombok.NoArgsConstructor;
import lombok.Setter;
import reactor.util.function.Tuple2;
import reactor.util.function.Tuples;

/**
 * <p>
 * 开发同步库表任务表记录表
 * </p>
 *
 * @author admin
 * @since 2021-06-17
 */
@NoArgsConstructor
public class SyncEnvProdLog extends SyncEnvLog {
    @Setter
    private String taskDetailId;

    @Setter
    private String taskId;

    public String getTaskId(){
        if (taskId == null) {
            Tuple2<String, String> tu= splitTaskAndDetailIds(super.getKey());
            if (tu != null) {
                return tu.getT1();
            }
        }
        return taskId;
    }
    public String getTaskDetailId(){
        if (taskDetailId == null) {
            Tuple2<String, String> tu= splitTaskAndDetailIds(super.getKey());
            if (tu != null) {
                return tu.getT2();
            }
        }
        return taskDetailId;
    }

    /**
     * 构建任务+明细id 唯一值
     */
    public static String getTaskAndDetailId(DapSyncProdEnvTaskDetail taskDetail){
        BmAssetUtils.notNulls(new Object[]{taskDetail, taskDetail.getTaskId(), taskDetail.getId()}, "不可为空");
        return taskDetail.getTaskId() + "#"+ taskDetail.getId();
    }
    /**
     * 构建任务+明细id
     */
    public static Tuple2<String, String> splitTaskAndDetailIds(String taskAndDetailId){
        if (taskAndDetailId == null || !taskAndDetailId.contains("#")){
            return null;
        }
        String[] arr = taskAndDetailId.split("#");
        return Tuples.of(arr[0], arr[1]);
    }

    public SyncEnvProdLog(SyncEnvLog src) {
        super.key = src.key;
        super.globalConfig = src.globalConfig;
        super.modelId = src.modelId;
        super.tableName = src.tableName;
        super.syncEnv = src.syncEnv;
        super.syncDdl = src.syncDdl;
        super.syncPtsql = src.syncPtsql;
        super.syncStatus = src.syncStatus;
        super.syncExecBy = src.syncExecBy;
        super.syncStartTime = src.syncStartTime;
        super.syncEndTime = src.syncEndTime;
        super.syncLog = src.syncLog;
        super.dataSourceId = src.dataSourceId;
        super.syncLogPath = src.syncLogPath;
        super.basePath = src.basePath;
        super.syncScript = src.syncScript;
        super.syncSandboxMock = src.syncSandboxMock;
    }

    /**
     * @return 初步构建日志实体
     */
    public static SyncEnvProdLog createLog(GlobalConfig globalConfig) {
        SyncEnvLog syncEnvLog = SyncEnvLog.createLog(globalConfig);
        SyncEnvProdLog envProdLog = new SyncEnvProdLog(syncEnvLog);
        return envProdLog;
    }
}
